package com.haoma.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haoma.entity.Link;
import com.haoma.entity.LinkApplyFor;
import com.haoma.exception.BlogException;
import com.haoma.mapper.LinkApplyForMapper;
import com.haoma.mapper.LinkMapper;
import com.haoma.minio.MinIOConfig;
import com.haoma.minio.MinIOConfigProperties;
import com.haoma.service.LinkService;
import com.haoma.vo.LinkApplyForVo;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Description: 友链相关接口
 */
@Service
public class LinkServiceImpl extends ServiceImpl<LinkMapper, Link> implements LinkService {


    // 注入minio配置类
    @Autowired
    private MinIOConfig minIOConfig;

    // 注入minio属性
    @Autowired
    private MinIOConfigProperties minIOConfigProperties;

    /**
     * 友链用户头像上传
     *
     * @param multipartFile
     * @return
     */
    public String fileUpload(MultipartFile multipartFile) {
        try {
            // 创建minio客户端
            MinioClient minioClient = minIOConfig.buildMinioClient();
            // 判断桶是否存在
            boolean isBucket = minioClient.bucketExists(BucketExistsArgs
                    .builder()
                    .bucket(minIOConfigProperties.getBucket()).build());
            if (!isBucket) {
                // 不存在创建一个桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minIOConfigProperties.getBucket()).build());
            } else {
                // 存在提示用户
                System.out.println("可以开始图片上传了");
            }
            // 存在
            // 构建图片路径 业务+日期格式+图片名称
            String date = DateUtil.format(new Date(), "yyyyMMdd");
            // 唯一id作为图片路径
            String uuid = UUID.randomUUID().toString().replace("-", "");
            // 组合＋业务
            String fileName = "web-linkuser-avatar" + "/" + date + "/" + uuid + multipartFile.getOriginalFilename();
            // 开始构建参数
            PutObjectArgs putObjectArgs = PutObjectArgs
                    .builder()
                    .bucket(minIOConfigProperties.getBucket())
                    .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                    .object(fileName)
                    .build();
            // 上传至minio客户端
            minioClient.putObject(putObjectArgs);
            // 将路径返回
            return minIOConfigProperties.getReadPath() + "/" + minIOConfigProperties.getBucket() + "/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Autowired
    private LinkMapper linkMapper;

    @Autowired
    private LinkApplyForMapper linkApplyForMapper;

    /**
     * 申请友链
     *
     * @param link
     * @return
     */
    public String applyForLink(Link link) {
        // 往友链表中插入数据
        linkMapper.insert(link);
        // 此时友链表中有id了然后就可以插入到申请表中了
        LambdaQueryWrapper<Link> linkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkLambdaQueryWrapper.eq(Link::getLinkAddress, link.getLinkAddress());
        // 开始查询
        Link linkDb = linkMapper.selectOne(linkLambdaQueryWrapper);
        if (linkDb == null) {
            return "申请失败";
        }
        // 往申请表中插入数据
        LinkApplyFor linkApplyFor = new LinkApplyFor();
        linkApplyFor.setLinkId(linkDb.getId());
        linkApplyFor.setName(linkDb.getName());
        linkApplyFor.setUrl(linkDb.getLinkUrl());
        // 开始插入
        linkApplyForMapper.insert(linkApplyFor);
        return "12小时内审核完成期待你的友链";
    }

    /**
     * 查询申请
     *
     * @param linkAddress
     * @return
     */
    public LinkApplyForVo queryApply(String linkAddress) {
        // 根据地址查询友链表
        LambdaQueryWrapper<Link> linkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkLambdaQueryWrapper.eq(Link::getLinkAddress, linkAddress);
        Link link = linkMapper.selectOne(linkLambdaQueryWrapper);
        // 校验
        if (link == null) {
            throw new BlogException("申请数据异常");
        }
        // 根据link_id查询友链申请表
        LinkApplyFor linkApplyFor = linkApplyForMapper
                .selectOne(new LambdaQueryWrapper<LinkApplyFor>()
                        .eq(LinkApplyFor::getLinkId, link.getId()));
        // 返回审核信息和状态
        LinkApplyForVo linkApplyForVo = new LinkApplyForVo();
        BeanUtils.copyProperties(linkApplyFor, linkApplyForVo);
        return linkApplyForVo;
    }

    /**
     * 查询所有的友链
     *
     * @return
     */
    public List<Link> list() {
        LambdaQueryWrapper<Link> linkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkLambdaQueryWrapper.eq(Link::getStatus, 1);
        List<Link> links = linkMapper.selectList(linkLambdaQueryWrapper.orderByDesc(Link::getUpdateTime));
        return links;
    }

    /**
     * 修改友链
     *
     * @param link
     */
    public void update(Link link) {
        // 查询
        LambdaQueryWrapper<Link> linkLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkLambdaQueryWrapper.eq(Link::getId, link.getId());
        Link linkDb = linkMapper.selectOne(linkLambdaQueryWrapper);
        // 拿到标识
        String identification = linkDb.getIdentification();
        // 校验
        if (!link.getIdentification().equals(identification)) {
            throw new BlogException("标识有误");
        }
        // 可以修改
        link.setStatus(3);
        // 修改友链表
        linkMapper.update(link,linkLambdaQueryWrapper);
        // 修改友链申请表
        LambdaQueryWrapper<LinkApplyFor> linkApplyForLambdaQueryWrapper = new LambdaQueryWrapper<>();
        linkApplyForLambdaQueryWrapper.eq(LinkApplyFor::getLinkId, linkDb.getId());
        LinkApplyFor linkApplyFor = linkApplyForMapper.selectOne(linkApplyForLambdaQueryWrapper);
        // 设置
        linkApplyFor.setName(link.getName());
        linkApplyFor.setUrl(link.getLinkUrl());
        linkApplyFor.setStatus(3);
        linkApplyForMapper.update(linkApplyFor, linkApplyForLambdaQueryWrapper);
    }
}
